﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using HandyControl.Controls;
using HandyControl.Data;
using Microsoft.Windows.Input;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PlaceOrder_Admin.ViewModels
{
    internal class ReviewViewModel:BindableBase
    {
        #region 依赖属性

        private ObservableCollection<ReviewMessage> reviewMessages;

        public ObservableCollection<ReviewMessage> ReviewMessages
        {
            get { return reviewMessages; }
            set { reviewMessages = value; RaisePropertiesChanged(); }
        }
        private bool isLoading = false;

        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading = value; RaisePropertyChanged(); }
        }

        private string loadingMessage = "加载中";

        public string LoadingMessage
        {
            get { return loadingMessage; }
            set { loadingMessage = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 数据总量
        /// </summary>
        private int totalDataCount;

        public int TotalDataCount
        {
            get { return totalDataCount; }
            set { totalDataCount = value; RaisePropertyChanged(); }
        }


        private bool isStartDateChecked;

        public bool IsStartDateChecked
        {
            get { return isStartDateChecked; }
            set { isStartDateChecked = value; RaisePropertyChanged(); }
        }


        private bool isEndDateChecked;

        public bool IsEndDateChecked
        {
            get { return isEndDateChecked; }
            set { isEndDateChecked = value; RaisePropertyChanged(); }
        }

        private DateTime _selectedStartDate = DateTime.Now.Date;
        public DateTime SelectedStartDate
        {
            get { return _selectedStartDate; }
            set
            {
                if (_selectedStartDate != value)
                {
                    _selectedStartDate = value;
                    RaisePropertyChanged();
                }
            }
        }
        private DateTime _selectedEndDate = DateTime.Now.Date;
        /// <summary>
        /// 筛选的交易日区间
        /// </summary>
        public DateTime SelectedEndDate
        {
            get { return _selectedEndDate; }
            set
            {
                if (_selectedEndDate != value)
                {
                    _selectedEndDate = value;
                    RaisePropertyChanged();
                }
            }
        }

        private ReviewMessage selectedReviewMessage;

        public ReviewMessage SelectedReviewMessage
        {
            get { return selectedReviewMessage; }
            set { selectedReviewMessage = value; RaisePropertiesChanged(); }
        }


        private string searchText;

        /// <summary>
        /// 查询过滤的文本框
        /// </summary>
        public string SearchText
        {
            get { return searchText; }
            set { searchText = value; RaisePropertyChanged(); }
        }

        private bool isSelected = false; //判断是不是处于搜索状态下
        public bool IsFirstStart = true;
        #endregion

        private readonly IDailyData _dailyData;
        public DelegateCommand SearchCommand { get; set; }
        public DelegateCommand ResetCommand { get; set; }

        public ReviewViewModel(IDailyData dailyData)
        {
            _dailyData = dailyData;
            Init();
            InitCommand();


        }
        private void Init()
        {
            ReviewMessages = _dailyData.GetAllReviewMessages().ToObservableCollection();
        }

        private void InitCommand()
        {
            SearchCommand = new DelegateCommand(SearchHandle);
            ResetCommand = new DelegateCommand(ResetHandle);
           
        }

        /// <summary>
        /// 查询方法（关键词查找）
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private async void SearchHandle()
        {
            if (IsStartDateChecked && IsEndDateChecked)
            {
                if (SelectedEndDate < SelectedStartDate)
                {
                    Growl.InfoGlobal("请检查日期，截止日不能小于开始日");
                    return;
                }
            }

            await SearchAllAsync();

            if (!string.IsNullOrEmpty(SearchText) || IsStartDateChecked == true || IsEndDateChecked == true)
            {
                // 创建一个临时列表来保存搜索结果
                var results = new List<ReviewMessage>();

                // 遍历所有交易，搜索符合条件的项目
                foreach (var item in ReviewMessages)
                {
                    if (SearchSelected(item, SearchText))
                    {
                        results.Add(item);
                    }
                }

                // 清空当前的ReviewMessages
                ReviewMessages.Clear();
                if (results.Count > 0)
                {
                    // 逐个添加搜索结果到ReviewMessages
                    foreach (var result in results)
                    {
                        ReviewMessages.Add(result);
                    }
                    isSelected = true;
                    TotalDataCount = ReviewMessages.Count;
                }
                else
                {
                    // 没有找到符合条件的记录，显示提示框
                    if (!IsFirstStart)
                    {
                        var messageBoxInfo = new MessageBoxInfo
                        {
                            Message = "找不到符合条件的记录",
                            Caption = "提示",
                            IconBrushKey = ResourceToken.InfoBrush,
                            IconKey = ResourceToken.InfoGeometry,
                            Button = MessageBoxButton.OK

                        };

                        //HandyControl.Controls.MessageBox.Show(messageBoxInfo);
                    }


                    // 重新加载所有数据
                    //SearchAll();
                    isSelected = false;
                    TotalDataCount = ReviewMessages.Count;
                }
            }
            else
            {
                // 如果没有输入搜索文本，加载所有数据
                //SearchAll();
                isSelected = false;
                TotalDataCount = ReviewMessages.Count;
            }
        }


        private bool SearchSelected(ReviewMessage item, string searchText)
        {
            // 检查搜索文本是否匹配
            bool textMatch = false;
            if (string.IsNullOrEmpty(searchText))
            {
                textMatch = true;
            }
            else
            {
                textMatch = IsContains(item.Reviewer, searchText) ||
                            IsContains(item.ReviewMessageInfo, searchText);
            }


            // 检查时间是否匹配
            bool timeMatch = true;
            // 检查日期的有效性


            // 如果启用开始日期过滤
            if (IsStartDateChecked && SelectedStartDate != null)
            {
                timeMatch = item.CreateTime >= SelectedStartDate;
            }

            // 如果启用截止日期过滤
            if (IsEndDateChecked && SelectedEndDate != null)
            {
                timeMatch &= item.CreateTime <= SelectedEndDate;
            }

            // 同时满足文本匹配和时间匹配
            return textMatch && timeMatch;
            //之后要加上时间的过滤
        }

        private bool IsContains(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1)) return false;
            if (str1.Contains(str2)) return true;
            else return false;
        }

        private void ResetHandle()
        {
            this.SelectedStartDate = DateTime.Now.Date;
            this.SelectedEndDate = DateTime.Now.Date;
            this.IsEndDateChecked = true;
            this.IsStartDateChecked = true;
            this.SearchText = string.Empty;
            this.SearchHandle();
        }

        private async Task SearchAllAsync()
        {
            ReviewMessages = new ObservableCollection<ReviewMessage>();
            var reviewMessages = await Task.Run(() => _dailyData.GetAllReviewMessages().ToObservableCollection());
            ReviewMessages = reviewMessages;

            if (ReviewMessages.Count != 0)
            {
                TotalDataCount = ReviewMessages.Count;
            }
        }
    }
    
}
